package com.alinesno.cloud.gateway.core.dispather.mina.server;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alinesno.cloud.gateway.core.dispather.SocketDispather;
import com.alinesno.cloud.gateway.core.dispather.mina.bean.BusinessServerBean;
import com.alinesno.cloud.gateway.core.dispather.mina.codec.MessageCodeFactory;

/**
 * Socket服务
 * @author WeiXiaoJin
 * @since 2020年1月31日 下午19:45:08
 */
public class MinaSocketServer {

	private static final Logger log = LoggerFactory.getLogger(MinaSocketServer.class) ; 

	private static final int DEFAULT_SERVER_OUTTIME = 45 ; 
	
	/**
	 * 启动socket服务
	 * @param server
	 * @throws IOException 
	 */
	public static void startServerByPort(BusinessServerBean server) throws IOException{
		int PORT = server.getServerPort() ;
		String SERVER_IP = server.getServiceIp() ; 
		
		long start = System.currentTimeMillis() ; 
	
		IoAcceptor acceptor = new NioSocketAcceptor();
		
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, server.getServerOuttime()==0?DEFAULT_SERVER_OUTTIME:server.getServerOuttime());
		
		acceptor.getFilterChain().addLast("logger", new LoggingFilter());
		acceptor.getFilterChain().addLast("codec",new ProtocolCodecFilter(new MessageCodeFactory(server))); // 自定义解码器
		acceptor.setHandler(new SocketDispather(server));
		
		acceptor.getSessionConfig().setReadBufferSize(2048);
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
		
		acceptor.bind(new InetSocketAddress(SERVER_IP , PORT));
		
		log.debug("启动 【{}】 netty socket服务:IP:{} , Port:{} 时间:{}ms " , server.getBusinessDesc() , server.getServerPort() , server.getServerPort() , (System.currentTimeMillis()-start));
		
	}
}